<?
require_once("mvc/action/Action.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $errors = new ActionMessages();

        $gallery =& $form->getGallery();
        $gallery->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            // process image
            $formImage =& $form->getFormImage();

            if(!$form->getDeleteImage() && $formImage["size"] > 0) {

                $image = $gallery->getImageRelatedByImageId();
                $thumb = $gallery->getImageRelatedByThumbnailId();

                require_once("cms/core/util/ImageProperties.php");
                $properties = new ImageProperties(
                    $request->getContext()->getInitParameter(_Core::SETTING_LIST)
                );

                require_once("cms/core/util/ImageProcessor.php");
                ImageProcessor::process(
                    $conn, $errors, $formImage,
                    $properties, $image, $thumb
                );

                // Set the generated ids
                $gallery->setThumbnailId($thumb->getImageId());
                $gallery->setImageId($image->getImageId());

            } else if($form->getDeleteImage()) {

                $image = $gallery->getImageRelatedByImageId();
                $thumb = $gallery->getImageRelatedByThumbnailId();

                require_once("cms/core/om/BinaryFilePeer.php");

                BinaryFilePeer::doDelete($thumb->getBinaryFile(), $conn);
                BinaryFilePeer::doDelete($image->getBinaryFile(), $conn);
            }

            if($gallery->getGalleryId() > 0) {
                $gallery->setGalleryId($gallery->getGalleryId());
                GalleryPeer::doUpdate($gallery, $conn);
            } else {
                $gallery->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                $gallery->setActive(_Core::AUTO_ACTIVATE);
                GalleryPeer::doInsert($gallery, $conn);
            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save", true));
            $this->log->error($e->getMessage());
        }

        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }

        $session  = $request->getSession();
        $listForm = $session->getAttribute("cms/galleryListForm");
        $listForm->setPage(0);
        $session->setAttribute("cms/galleryListForm", $listForm);

        return $mapping->findForward("success");

    }

}
?>